#import "AirplayPlusPlugin.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface AirplayPlusPlugin()<FlutterStreamHandler>

@property (nonatomic,strong) FlutterEventSink sink;
@property (nonatomic, strong) MPVolumeView *volumeView;

@end

@implementation AirplayPlusPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"airplay_plus"
                                     binaryMessenger:[registrar messenger]];
    AirplayPlusPlugin* instance = [[AirplayPlusPlugin alloc] init];
    [registrar addMethodCallDelegate:instance channel:channel];
    
    FlutterEventChannel * event = [FlutterEventChannel eventChannelWithName:@"airplay_plus_eventChannel" binaryMessenger:registrar.messenger];
    [event setStreamHandler:instance];
    
}

// 启动时检查一下
- (NSInteger)checkStatus{
    // 获取当前音频路由
    AVAudioSession *session = [AVAudioSession sharedInstance];
    NSArray *currentRoute = session.currentRoute.outputs;

    // 检查是否有AirPlay设备连接
    BOOL isAirPlayConnected = NO;
    for (AVAudioSessionPortDescription *port in currentRoute) {
        if ([port.portType isEqualToString:AVAudioSessionPortAirPlay]) {
            isAirPlayConnected = YES;
            break;
        }
    }

    if (isAirPlayConnected) {
        [self toFlutter:@1];
        return 1;
    } else {
        [self toFlutter:@0];
        return 0;
    }
    
}

- (FlutterError* _Nullable)onListenWithArguments:(id _Nullable)arguments
                                       eventSink:(FlutterEventSink)events{
    self.sink = events;
    [self checkStatus];
    
    return nil;
}
- (FlutterError* _Nullable)onCancelWithArguments:(id _Nullable)arguments{
    return nil;
}

// 告诉flutter 连接状态
- (void)toFlutter:(NSNumber *)connect{
    if (!self.sink) {
        NSLog(@"airplay plus插件 出现了sink没有值的情况");
        return;
    }
    
    self.sink(@{@"type":@"connect",@"status":connect});
}


- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
  if ([@"getPlatformVersion" isEqualToString:call.method]) {
    result([@"iOS " stringByAppendingString:[[UIDevice currentDevice] systemVersion]]);
  } else if ([@"airPlay" isEqualToString:call.method]) {
      if (!self.volumeView) {
          MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame:CGRectZero];
          volumeView.alpha = 0;
          UIViewController *vc = [[[UIApplication sharedApplication] keyWindow] rootViewController];
          [vc.view addSubview:volumeView];
          self.volumeView = volumeView;
          
          [[NSNotificationCenter defaultCenter] addObserver:self
                                                   selector:@selector(audioRouteChanged:)
                                                       name:AVAudioSessionRouteChangeNotification
                                                     object:nil];
      }
      
      // 让MPVolumeView展示AirPlay按钮
      for (UIView *subview in self.volumeView.subviews) {
          if ([subview isKindOfClass:[UIButton class]]) {
              UIButton *button = (UIButton *)subview;
              [button sendActionsForControlEvents:UIControlEventTouchUpInside];
              break;
          }
      }
      
      result(nil);
  } else if ([@"getAirPlayStatus" isEqualToString:call.method]) {
      result(@([self checkStatus]));
  }
  else {
    result(FlutterMethodNotImplemented);
  }
}

// 监听AirPlay连接状态
- (void)audioRouteChanged:(NSNotification *)notification {
    AVAudioSessionRouteDescription *currentRoute = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription *output in currentRoute.outputs) {
        if ([output.portType isEqualToString:AVAudioSessionPortAirPlay]) {
            [self toFlutter:@1];
        } else {
            [self toFlutter:@0];
        }
    }
}

@end
